<?php
/**
 * Admin User_Admin_Model
 * @filesource
 */
/**
 * Namespace
 */
namespace plurious\apps\admin\model;
/**
 * Dependencies
 */
use plurious\apps\admin\model\Auth_Forge;
use framework\library\Model;
use framework\Front;
/**
 * User_Admin_Model 
 * 
 * Extends Model. 
 *
 * Auth_Model CRUD functions for user authentication
 *
 * A unique model that provides for a standard starting point - the user data
 * table - and then automagically allows the developer/user to add table 
 * columns with no extra effort.  A simple call to the add() method using 
 * column=>data array elements will add any non-existant columns in the array.
 * These newly added and permanent columns can then be used for all future 
 * operations on that table.
 * 
 * Features provided by this function:
 * Add user            // Create in crud land
 * Get user            // Retrieve in crud land
 * Update user         // Update - hey I got one right
 * Delete user         // Delete - There's two! 
 * List All users
 * Activate user
 * Deactivate user
 * Lock user
 * Unlock user
 *
 * @author Randy Casburn <randy@plurious.com>
 * @copyright Copyright Plurious Software, all rights reserved
 * @license MIT
 * @license http://www.opensource.org/licenses/mit-license.html
 * @link http://plurious.com/framework/documentation/classes/Front.html
 * @version 2.1
 * 
 * @uses framework\library\Model
 * @uses framework\Front
 * @uses plurious\apps\admin\model\Auth_Forge
 */
class User_Admin_Model extends Model {

    private $registry;
    private $session;
    private $config;
    private $forge; //as in steal
    private $auth_table;
    private $useridCol;
    private $usernameCol;
    private $passwordCol;

    /**
     * Provides access to the system registry and base classes.
     * 
     * If authentication data is stored in a separate database provide the
     * relavent data to the construtor (and parent constructor).
     * 
     * @param string $name Database name
     * @param string $user Database username
     * @param string $pw Database password
     * @param string $type Database type (MSSQL, MYSQL, PGSQL, SQLITE, etc.)
     * @param string $host Database host
     * @param string $port Database port
     */
    public function __construct($name= DB_DATABASE, $user= DB_USERNAME, $pw= DB_PASSWORD, $type = DB_DRIVER, $host= DB_HOSTNAME, $port="") {
        parent::__construct($name, $user, $pw, $type, $host, $port);
        $this->registry = Front::getInstance();
        $this->session = $this->registry->get('session');
        $this->config = $this->registry->get('config');
//        $this->forge = new Auth_Forge();
        $this->auth_table = $this->config->get('auth_table');
        $this->useridCol = $this->config->get('UserIdCol');
        $this->usernameCol = $this->config->get('UserNameCol');
        $this->passwordCol = $this->config->get('PasswordCol');
    }

    /**
     *  Adds a user record to auth_table.
     * 
     * @uses Auth_Forge - Magically add columns to authentication table
     * @see Auth_Forge
     * @param array $columnData Collection of rows and values to add
     * @return int The lastInsertId() or the error id
     */
    public function add(array $columnData) {
        // Magically add non-existant columns to the $auth_table
//        $this->forge->prepareNewColumns($columnData, $this->db);
        // build query - IGNORE is needed to avoid the DUPLICATE UNIQUE key errors. We must test for an insert_id() to make sure //
        // a row was actually added.  If it was not, it was likely due to a duplicate username being entered.
        //$q = "INSERT IGNORE INTO ".$this->auth_table." (".implode(',',array_keys($core)).") VALUES(".implode(',',array_values($core)).")";
        //$query = $this->db->query($q);
        $lastInsertId = $this->db->insert($this->auth_table, $columnData);
        if ($lastInsertId) {
            return $lastInsertId;
        } else {
            return AUTH_ACTION_DUPLICATE_USERNAME;
        }
    }

    /**
     * Gets a single record from the authentication database or throws and error
     * 
     * @param int $uid User Id
     * @return mixed Array of result rows or an int error indicator
     */
    public function getUser($uid) {
        $result = $this->get($this->auth_table, array($this->useridCol => $uid));
        if (!$result) return AUTH_ACTION_NOUSERS_TOLIST;
        if (count($result) > 1) return AUTH_ACTION_DUPLICATE_USERNAME;
        return $result;
    }
    /**
     * Retrieves a list of all user records
     * 
     * @return array List of all recorded users
     */
    public function getAll() {
        $result = $this->db->get($this->auth_table);
        if(!$result)return AUTH_ACTION_NOUSERS_TOLIST;
        return $result;
        }
    /**
     * Update a user record
     * 
     * @param array $columnData
     * @return int Success or Error Id
     */
    public function updateUser(array $columnData) {
        $updateSet = array();
        foreach ($columnData as $col => $val) {
            if ($col != $this->useridCol)
                $updateSet[$col] = $val;
        }
        $result = $this->db->update($this->auth_table, $updateSet, array($this->useridCol => $columnData[$this->useridCol]));
        if ($result) {
            return AUTH_ACTION_UPDATE_SUCCESS;
        } else {
            return AUTH_ACTION_UPDATE_FAILED;
        }
    }

    /**
     * Permanently removes the record
     *
     * @param int $uid
     * @param bool $isSelf
     * @return int Success or Error Id
     */
    public function deleteUser($uid, $isSelf = false) {
        $result = $this->db->delete($this->auth_table, array($this->useridCol => $uid));
        if(!$result) return AUTH_ACTION_DELETE_FAILED;
        if (isSelf) {
            $this->session->kill();
        }
        return AUTH_ACTION_DELETE_SUCCESS;
    }

    /**
     * Lock a user account and immediately destroy their session (log them out)
     * 
     * @param int $uid
     * @return int Success or Error Id
     */
    public function lock($uid) {
        $result = $this->db->update($this->auth_table, array('is_locked' => 1), array($this->useridCol => $uid));
        if (!$result) return AUTH_ACTION_LOCK_FAILED;
        $this->session->kill($uid);
        return AUTH_ACTION_LOCK_SUCCESS;
    }
    /**
     * Unlock a user account
     * 
     * @param int $uid
     * @return int Success or Error Id
     */
    public function unlock($uid) {
        $result = $this->db->update($this->auth_table, array('is_locked' => 0), array($this->useridCol => $uid));
        if (!$result) return AUTH_ACTION_UNLOCK_FAILED;

        return AUTH_ACTION_UNLOCK_SUCCESS;
    }
    /**
     * Activate a user account
     * 
     * Could be used with a registration system to respond to an automated
     * email notification, etc.
     * 
     * @param int $uid
     * @return int Success or Error Id
     */
    public function activate($uid) {
        $result = $this->db->update($this->auth_table, array('is_active' => 1), array($this->useridCol => $uid));
        if (!$result) return AUTH_ACTION_ACTIVATE_FAILED;

        return AUTH_ACTION_ACTIVATE_SUCCESS;
    }

    /**
     * Dectivate a user account
     * 
     * Does not delete the record...can be reactivated at any time.
     * 
     * @param int $uid
     * @return int Success or Error Id
     */
    public function deactivate($uid) {
        $result = $this->db->update($this->auth_table, array('is_active' => 0), array($this->useridCol => $uid));
        if (!$result) return AUTH_ACTION_DEACTIVATE_FAILED;
        
        $this->session->kill($uid);
        return AUTH_ACTION_DEACTIVATE_SUCCESS;
    }

}

?>